/**
 * @author trex279
 */
/*
 * beware of the code on this page. It will rip your eyes out and then eviscerate you at leisure.
 */
var userName_g = "";
var errorFlag = false;
var loggedinFlag = false;

$(document).ready(function(){
		$('#redditFrame').css('display','none');
});

function iframeLoaded(){
	//if(!loggedinFlag) window.parentSandboxBridge.showLoginform();
	$('#redditFrame').css('display','block');
	checkIfLoggedIn();
}

var childsExposedObject = {};
childsExposedObject.redditLogin = function(userName, password){
	userName_g = userName;
	var frameContents = $('#redditFrame').contents();
	frameContents.find('#login_login-main').find("input[name='user']").val(userName);
	frameContents.find('#login_login-main').find("input[name='passwd']").val(password);
	frameContents.find('#rem-login-main').attr('checked', true);
	frameContents.find('#remember-me button').trigger('click');
	var t = setTimeout("checkIfLoggedIn();",5000);
}

childsExposedObject.redditLogout = function(){
	var frameContents = $('#redditFrame').contents();
	frameContents.find('#header-bottom-right .logout').trigger('submit');
	checkIfLoggedIn();
}

window.childSandboxBridge = childsExposedObject;

//sorry for the terrible code here. But remotely controlling a website with just javascript is a bitch. And especially so in air with its damn sandboxing
var i = 0;

var checkIfLoggedIn = function(){
	i++;
	if(i==3) return;
	
	var frameContents = $('#redditFrame').contents();
	if(frameContents.find('#header-bottom-right .user a').html()=="register" && frameContents.find('#login_login-main .WRONG_PASSWORD').html()!="invalid password"){
		var t = setTimeout("checkIfLoggedIn();",5000);
		if(!errorFlag){
			window.parentSandboxBridge.loginResult("false", userName_g);
			loggedinFlag = false;
		} 
	}
	else if(frameContents.find('#login_login-main .WRONG_PASSWORD').html()=="submitting..." || frameContents.find('#login_login-main .WRONG_PASSWORD').html()=="redirecting..."){
		t = setTimeout("checkIfLoggedIn();",5000);
		
	}
	else 
		if(frameContents.find('#login_login-main .WRONG_PASSWORD').html()=="invalid password"){
			window.parentSandboxBridge.loginResult("error", userName_g);
			frameContents.find('#login_login-main .WRONG_PASSWORD').html("");
			errorFlag = true;
			loggedinFlag = false;
		}
		else
			if(userName_g!="" && frameContents.find('#header-bottom-right .user a').html()==userName_g){
				if(!loggedinFlag){
					window.parentSandboxBridge.loginResult("true", userName_g);
					loggedinFlag = true;
					errorFlag = false;
				} 
			}
			else if(frameContents.find('#header-bottom-right .logout a').html()=="logout" ){
					if(!loggedinFlag){
						userName_g = frameContents.find('#header-bottom-right .user a').html();
						window.parentSandboxBridge.loginResult("true", userName_g);
						loggedinFlag = true;
						errorFlag = false;
				} 
			}
	return;
}

//I have created a monster. *sigh*
//If you can fix this, all my karma is yours
